import datetime
import time
# import jwt
# key = 'ldd0ewk6_*e-9mejs(wo8x(il2&p9c-1f8+0f7wd8f69(d-)pe*'
#
#
# def encodejwt(dict):
#     payload = {
#         'data': {'username': '11111', 'role_data': '111111'}
#     }
#     encodes = jwt.encode(payload, key, algorithm='HS256')
#     return encodes


# def decodejwt(token):
#     dicts = jwt.decode(token, key, algorithms=['HS256'])
#     return dicts


def encode_key(user,date):
    key = 'ehr{#@}d{deec{21hx8}{e2ccr3-_3+3dc}[ec[]eeedc'

    data = "{'user':'"+ user +"','date':'"+ date +"'}"
    if len(data) % 2 != 0:
        data += '6'
        d1 = data[0:len(data):2][::-1]
        d2 = data[1:len(data):2][::-1]
        data_len = (len(data)+1)//2
        print(d2)
    else:
        # data += '6'
        d1 = data[0:len(data) + 1:2][::-1]
        d2 = data[1:len(data) + 1:2][::-1]
        data_len = len(data)//2


    keys = ''
    for i in range(data_len):
        keys += f'{d1[i] + key[i] + d2[i] + key[-i]}'
    if data[-1]=='6':
        keys += '6'

    return keys

def docode_key(keys):
    key_deco = 'ehr{#@}d{deec{21hx8}{e2ccr3-_3+3dc}[ec[]eeedc'
    ds1 = ''
    ds2 = ''
    ds3 = ''



    try:
        flag = 0
        if keys[-1]=='6':
            keys = keys[:-1]
            flag = 1
            # keys = base64.a85decode(keys)
            data_len = (len(keys))/4
        else:
            # keys = base64.b64decode(keys)
            data_len = len(keys)/4

        for i in range(int(data_len)):
            ds1 += keys[i*4]
            ds2 += keys[i*4+1]
            ds3 += keys[i*4+2]

        # 判断是否被修改
        if ds2 != key_deco[:int(data_len)]:
            return None

        s = ''
        for i in range(int(data_len)):
            s += (ds1[::-1][i]+ds3[::-1][i])
        if flag == 1:
            s = s[:-1]
        ss = dict(eval(s))
        return ss
    except:
        return None


def check_keys(keys):
    strdata = docode_key(keys)
    if strdata is None:
        return 'err'
    dicts = dict(strdata)

    datestr = dicts['date']
    datetime = time.strptime(datestr, '%Y-%m-%d %H:%M:%S')
    if datetime <= time.localtime():
        return 'errB'

    return 'ok'



if __name__ == '__main__':
    date = '2021-10-12 00:00:00'
    keys = encode_key('keys',date)
    print(keys)
    data = check_keys(keys)
    print(data)

    # token = encodejwt({'name':'aaaa'})
    # print(token)
    # data = decodejwt(token)
    # print(data)
